﻿#include "graph.h"
#include "ui_graph.h"

Graph::Graph(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Graph)
{

    ui->setupUi(this);

    this->init();

}

void Graph::init(){

    scene = new MyMap();
    graphView = new MyGView(this);

    //scene->setSceneRect( 0,0,100,100 );
    graphView->setScene(scene);

    this->centralWidget()->layout()->addWidget( graphView );
    //this->centralWidget()->layout()->addWidget(graphView);

    graphView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    graphView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    //graphView->setCursor(Qt::OpenHandCursor);

    graphView->setFocus();

    QObject::connect( graphView,SIGNAL(gvPress(QPoint*)),scene,SLOT(startVertex(QPoint*)));
    QObject::connect( graphView,SIGNAL(rbClick(QPoint*)),scene,SLOT(startstopLine(QPoint*)));
    QObject::connect( scene,SIGNAL(calculateMatrix()),this,SLOT(calculate()));
    QObject::connect( this,SIGNAL(changeOrient(bool *)),scene,SLOT(changeOrient(bool *)));

}

void Graph::calculate(){

    QList<QGraphicsItem *> all_items;
    all_items = scene->items();

    QList<VertexItem *> items;

    VertexItem *item;
    item = NULL;

    for ( int i=0; i<all_items.size(); i++ ){
        item = dynamic_cast<VertexItem *>( all_items.at(i) );
        if ( item ){
            items.append( item );
        }else{
            item = NULL;
        }
    }

    int size;
    size = items.size()-1;
    QStringList *ans = new QStringList();
    QString     *tmp = new QString();

    ans->clear();
    tmp->clear();

    for ( int i=size; i>=0;i-- ){
        for ( int j=size; j>=0;j-- ){
            if ( i!=j && items.at(i)->isLinkWith( items.at(j)->getIndex() ) ){
                tmp->append( QString("a%1%2\t").arg( items.at(i)->getIndex() ).arg( items.at(j)->getIndex() ) );
            }else{
                tmp->append("0\t");
            }

        }
        ans->append(*tmp);
        tmp->clear();
    }

    //qDebug()<<ans->join("\n");

    QApplication::clipboard()->setText(ans->join("\n"));

    QImage *image = new QImage(scene->width(), scene->height(), QImage::Format_ARGB32_Premultiplied);
    image->fill(QColor(Qt::white).rgb());


    QPainter painter(image);
    scene->render(&painter);
    image->save("result.png");


}

Graph::~Graph()
{
    delete ui;
}

void Graph::on_orientBox_clicked(bool checked)
{
    emit changeOrient(&checked);
}
